<template>
  <div class="payment-detail-tab">

    <!-- 搜索过滤 -->
    <div class="search-section" style="margin-bottom: 20px; padding: 16px; background: #f5f7fa; border-radius: 8px;">
      <el-form :model="searchForm" inline>
        <el-form-item label="支付类型">
          <el-select v-model="searchForm.paymentType" placeholder="全部" style="width: 120px;">
            <el-option label="全部" value="" />
            <el-option label="充值" value="recharge" />
            <el-option label="扣款" value="deduction" />
          </el-select>
        </el-form-item>
        <el-form-item label="付款渠道">
          <el-select v-model="searchForm.paymentChannel" placeholder="全部" style="width: 120px;">
            <el-option label="全部" value="" />
            <el-option label="扫码充值" value="扫码充值" />
            <el-option label="国际汇款" value="国际汇款" />
            <el-option label="余额提现" value="余额提现" />
            <el-option label="转给好友" value="转给好友" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="全部" style="width: 120px;">
            <el-option label="全部" value="" />
            <el-option label="成功" value="success" />
            <el-option label="失败" value="failed" />
            <el-option label="处理中" value="pending" />
            <el-option label="已撤销" value="revoked" />
          </el-select>
        </el-form-item>
        <el-form-item label="支付日期">
          <el-date-picker v-model="searchForm.dateRange" type="daterange" range-separator="至" start-placeholder="开始" end-placeholder="结束" style="width: 240px;" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSearch">查询</el-button>
          <el-button @click="onReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 统计信息 -->
    <div class="payment-summary" style="margin: 16px 0; padding: 16px; background: #f5f7fa; border-radius: 8px;">
      <el-row :gutter="24">
        <el-col :span="8">
          <div class="summary-item">
            <div class="summary-label">充值总金额</div>
            <div class="summary-value recharge-total">¥{{ totalRechargeAmount.toLocaleString() }}</div>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="summary-item">
            <div class="summary-label">扣款总金额</div>
            <div class="summary-value deduction-total">¥{{ totalDeductionAmount.toLocaleString() }}</div>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="summary-item">
            <div class="summary-label">当前余额</div>
            <div class="summary-value current-balance">¥{{ currentBalance.toLocaleString() }}</div>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 支付记录表格 -->
    <el-table :data="pagedData" border stripe style="width: 100%; margin-top: 16px;">
      <el-table-column prop="id" label="记录ID" width="120" />
      <el-table-column prop="payment_type" label="类型" width="100">
        <template #default="scope">
          <div style="display: flex; align-items: center; gap: 4px;">
            <!-- 退款记录只显示退款标签 -->
            <el-tag v-if="scope.row.id.startsWith('REFUND')" type="warning">退款</el-tag>
            <!-- 撤销记录显示撤销标签 -->
            <el-tag v-else-if="scope.row.id.startsWith('REVERSE')" type="info">撤销</el-tag>
            <!-- 其他记录显示充值或扣款标签 -->
            <el-tag v-else :type="scope.row.payment_type === 'recharge' ? 'success' : 'danger'">
              {{ scope.row.payment_type === 'recharge' ? '充值' : '扣款' }}
            </el-tag>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="amount" label="金额" width="120">
        <template #default="scope">
          <span :class="scope.row.payment_type === 'recharge' ? 'amount-positive' : 'amount-negative'">
            {{ scope.row.payment_type === 'recharge' ? '+' : '-' }}{{ scope.row.amount }}
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="balance" label="余额" width="120">
        <template #default="scope">
          <span :class="scope.row.balance && scope.row.balance.startsWith('-') ? 'balance-negative' : 'balance-positive'">
            {{ scope.row.balance || '¥0' }}
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="currency" label="货币单位" width="100">
        <template #default="scope">
          <el-tag type="warning">JPY</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="payment_channel" label="付款渠道" width="120">
        <template #default="scope">
          <el-tag type="primary">{{ getChannelName(scope.row.payment_channel) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="remark" label="备注" min-width="200" show-overflow-tooltip>
        <template #default="scope">
          <div>
            <span>{{ scope.row.remark }}</span>
            <div v-if="scope.row.related_record_id" style="margin-top: 4px; display: flex; align-items: center; gap: 4px;">
              <el-tag type="info" size="small">
                关联: {{ scope.row.related_record_id }}
              </el-tag>
              <el-button 
                type="primary" 
                size="small" 
                text 
                @click="copyToClipboard(scope.row.related_record_id)"
                style="padding: 2px 4px; min-width: unset;"
              >
                <el-icon><CopyDocument /></el-icon>
              </el-button>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="100">
        <template #default="scope">
          <el-tag :type="getStatusType(scope.row.status)">
            {{ getStatusName(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="payment_date" label="支付日期" width="160" />
      <el-table-column prop="operator" label="操作人" width="100" />
              <el-table-column label="操作" width="180" fixed="right">
          <template #default="scope">
            <div style="display: flex; gap: 4px;">
              <el-button size="small" @click="viewDetail(scope.row)">查看明细</el-button>
              <el-button 
                v-if="canRevoke(scope.row)"
                size="small" 
                type="danger" 
                @click="revokePayment(scope.row)"
                :disabled="scope.row.status !== 'success'"
              >
                撤销
              </el-button>
            </div>
          </template>
        </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div style="margin-top: 16px; text-align: right;">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 30, 50]"
        :total="filteredData.length"
        layout="total, sizes, prev, pager, next, jumper"
      />
    </div>

    <!-- 查看明细弹窗 -->
    <el-dialog v-model="showDetailDialog" title="支付明细" width="600px">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="记录ID">{{ detailData.id }}</el-descriptions-item>
        <el-descriptions-item label="支付类型">
          <div style="display: flex; align-items: center; gap: 4px;">
            <el-tag :type="detailData.payment_type === 'recharge' ? 'success' : 'danger'">
              {{ detailData.payment_type === 'recharge' ? '充值' : '扣款' }}
            </el-tag>
            <el-tag v-if="detailData.id && detailData.id.startsWith('REFUND')" type="warning" size="small">退款</el-tag>
            <el-tag v-if="detailData.id && detailData.id.startsWith('REVERSE')" type="info" size="small">撤销</el-tag>
          </div>
        </el-descriptions-item>
        <el-descriptions-item label="金额">{{ detailData.amount }}</el-descriptions-item>
        <el-descriptions-item label="货币单位">
          <el-tag type="warning">JPY</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="付款渠道">{{ getChannelName(detailData.payment_channel) }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="getStatusType(detailData.status)">
            {{ getStatusName(detailData.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="支付日期" :span="2">{{ detailData.payment_date }}</el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">
          <div>
            <span>{{ detailData.remark || '无' }}</span>
            <div v-if="detailData.related_record_id" style="margin-top: 8px; display: flex; align-items: center; gap: 8px;">
              <el-tag type="info" size="small">
                关联记录: {{ detailData.related_record_id }}
              </el-tag>
              <el-button 
                type="primary" 
                size="small" 
                text 
                @click="copyToClipboard(detailData.related_record_id)"
                style="padding: 4px 8px; min-width: unset;"
              >
                <el-icon><CopyDocument /></el-icon>
                复制
              </el-button>
            </div>
          </div>
        </el-descriptions-item>
        <el-descriptions-item label="交易流水号" :span="2">{{ detailData.transaction_id }}</el-descriptions-item>
        <el-descriptions-item label="操作人" :span="2">{{ detailData.operator || '系统' }}</el-descriptions-item>
        <el-descriptions-item label="创建时间" :span="2">{{ detailData.create_time }}</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <el-button @click="showDetailDialog = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { CopyDocument } from '@element-plus/icons-vue'
import { getPaymentRecordsAPI, savePaymentRecordAPI } from '@/services/api'
import { getMockPaymentRecords } from '@/mock/paymentRecords'
import type { PaymentRecord } from '@/services/database'

const props = defineProps<{
  member: any
}>()

// 调试：打印props
console.log('PaymentDetailTab props:', props.member)

// 搜索表单
const searchForm = ref({
  paymentType: '',
  paymentChannel: '',
  status: '',
  dateRange: []
})

// 分页
const currentPage = ref(1)
const pageSize = ref(10)

// 支付记录数据
const paymentRecords = ref<PaymentRecord[]>([])
const showDetailDialog = ref(false)
const detailData = ref<any>({})

// 从数据库获取支付记录数据
const generatePaymentRecords = async (): Promise<PaymentRecord[]> => {
  const memberId = props.member.id
  console.log('正在获取会员ID:', memberId, '类型:', typeof memberId)
  
  // 测试IndexedDB是否可用
  if (!window.indexedDB) {
    console.error('IndexedDB不可用')
    return []
  }
  
  try {
    // 优先使用 Mock 模式
    const isMock = ((): boolean => {
      const flag = localStorage.getItem('mockPayments')
      return flag === '1' || /[?&]mock=1(&|$)/.test(window.location.search)
    })()
    if (isMock) {
      const mock = getMockPaymentRecords(memberId)
      console.log('使用Mock支付记录，条数:', mock.length)
      if (mock.length > 0) return mock
      // 没有则继续走初始化逻辑
    }

    // 从数据库获取记录
    const dbRecords = await getPaymentRecordsAPI(memberId)
    console.log('数据库返回记录数:', dbRecords.length)
    
    // 调试：打印数据库中的记录详情
    if (dbRecords.length > 0) {
      console.log('数据库中的记录详情:')
      dbRecords.forEach((record, index) => {
        console.log(`[${index}] ID: ${record.id}, 类型: ${record.payment_type}, 金额: ${record.amount}, 余额: ${record.balance}, 时间: ${record.payment_date}`)
      })
    }
    
    // 如果有数据库记录，使用数据库记录
    if (dbRecords.length > 0) {
      console.log(`从数据库获取到 ${dbRecords.length} 条支付记录`)
      return dbRecords
    }
    
    // 数据库中没有记录，根据会员ID生成不同的初始数据
    console.log('数据库中没有记录，生成初始数据')
    let initialRecords: PaymentRecord[] = []
    
    if (memberId === '10001') {
      // 用户1：初始余额8888円
      initialRecords = [
        {
          id: 'TX20250601830001',
          member_id: memberId,
          payment_type: 'recharge',
          amount: '8888',
          balance: '¥8,888',
          currency: 'JPY',
          payment_channel: '扫码充值',
          remark: '初始充值',
          status: 'success',
          payment_date: '2025-06-01 08:30:15',
          transaction_id: 'TXN20250601830001',
          create_time: '2025-06-01 08:30:15',
          operator: '系统',
          related_record_id: '',
          is_revoked: 0
        }
      ]
    } else if (memberId === '10003') {
      // 用户3：初始余额0円，无记录
      initialRecords = []
    } else {
      // 其他用户：默认测试数据
      initialRecords = [
        {
          id: 'TX20250601830001',
          member_id: memberId,
          payment_type: 'recharge',
          amount: '10000',
          balance: '¥10,000',
          currency: 'JPY',
          payment_channel: '扫码充值',
          remark: '初始充值',
          status: 'success',
          payment_date: '2025-06-01 08:30:15',
          transaction_id: 'TXN20250601830001',
          create_time: '2025-06-01 08:30:15',
          operator: '系统',
          related_record_id: '',
          is_revoked: 0
        },
        {
          id: 'TX20250602145002',
          member_id: memberId,
          payment_type: 'deduction',
          amount: '2000',
          balance: '¥8,000',
          currency: 'JPY',
          payment_channel: '余额提现',
          remark: '余额提现',
          status: 'success',
          payment_date: '2025-06-02 11:45:22',
          transaction_id: 'TXN20250602145002',
          create_time: '2025-06-02 11:45:22',
          operator: '系统',
          related_record_id: '',
          is_revoked: 0
        },
        {
          id: 'TX20250603120003',
          member_id: memberId,
          payment_type: 'recharge',
          amount: '5000',
          balance: '¥13,000',
          currency: 'JPY',
          payment_channel: '国际汇款',
          remark: '国际汇款充值',
          status: 'success',
          payment_date: '2025-06-03 12:00:33',
          transaction_id: 'TXN20250603120003',
          create_time: '2025-06-03 12:00:33',
          operator: '管理员',
          related_record_id: '',
          is_revoked: 0
        }
      ]
    }
    
    // 保存初始数据到数据库
    console.log('开始保存初始数据到数据库...')
    for (const record of initialRecords) {
      try {
        await savePaymentRecordAPI(record)
        console.log('保存记录成功:', record.id)
      } catch (error) {
        console.error('保存记录失败:', record.id, error)
      }
    }
    
    console.log('初始数据已保存到数据库，返回记录数:', initialRecords.length)
    return initialRecords
  } catch (error) {
    console.error('获取支付记录失败:', error)
    return []
  }
}

// 初始化支付记录
onMounted(async () => {
  if (props.member && props.member.id) {
    paymentRecords.value = await generatePaymentRecords()
    // 计算余额
    recalculateAllBalances()
  }
})

// 监听member变化，重新加载数据
watch(() => props.member, async (newMember, oldMember) => {
  console.log('PaymentDetailTab watch触发:', { newMember, oldMember })
  if (newMember && newMember.id) {
    console.log('会员信息变化，重新加载支付记录:', newMember.id)
    try {
      const records = await generatePaymentRecords()
      console.log('获取到的记录数:', records.length)
      paymentRecords.value = records
      // 计算余额
      recalculateAllBalances()
    } catch (error) {
      console.error('加载支付记录失败:', error)
      paymentRecords.value = []
    }
  } else {
    console.log('会员信息无效或ID为空')
  }
}, { immediate: true, deep: true })

// 不再提供手动刷新函数

// 过滤数据
const filteredData = computed(() => {
  const filtered = paymentRecords.value.filter(record => {
    // 支付类型
    if (searchForm.value.paymentType && record.payment_type !== searchForm.value.paymentType) return false
    // 付款渠道
    if (searchForm.value.paymentChannel && record.payment_channel !== searchForm.value.paymentChannel) return false
    // 状态
    if (searchForm.value.status && record.status !== searchForm.value.status) return false
    // 日期范围
    if (searchForm.value.dateRange && searchForm.value.dateRange.length === 2) {
      const recordDate = new Date(record.payment_date).getTime()
      const [start, end] = searchForm.value.dateRange.map(v => new Date(v).getTime())
      if (recordDate < start || recordDate > end) return false
    }
    return true
  })
  
  // 按支付时间倒序排序
  return filtered.sort((a, b) => {
    const dateA = new Date(a.payment_date).getTime()
    const dateB = new Date(b.payment_date).getTime()
    return dateB - dateA
  })
})

// 分页数据
const pagedData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredData.value.slice(start, end)
})

// 统计计算
const revokedRecords = computed(() => paymentRecords.value.filter(r => r.status === 'revoked'))
const refundRecords = computed(() => paymentRecords.value.filter(r => r.id.startsWith('REFUND')))
const reverseRecords = computed(() => paymentRecords.value.filter(r => r.id.startsWith('REVERSE')))
const successRecords = computed(() => paymentRecords.value.filter(r => r.status === 'success'))

// 可撤销记录（30天内且状态为成功）
const revokableRecords = computed(() => paymentRecords.value.filter(r => {
  if (r.status !== 'success') return false
  
  const paymentDate = new Date(r.payment_date)
  const currentDate = new Date()
  const timeDiff = currentDate.getTime() - paymentDate.getTime()
  const daysDiff = timeDiff / (1000 * 3600 * 24)
  
  return daysDiff <= 30
}))

const revokedRate = computed(() => {
  if (paymentRecords.value.length === 0) return 0
  return Math.round((revokedRecords.value.length / paymentRecords.value.length) * 100)
})

const refundRate = computed(() => {
  if (paymentRecords.value.length === 0) return 0
  return Math.round((refundRecords.value.length / paymentRecords.value.length) * 100)
})

const reverseRate = computed(() => {
  if (paymentRecords.value.length === 0) return 0
  return Math.round((reverseRecords.value.length / paymentRecords.value.length) * 100)
})

// 充值总金额计算 - 统计所有有效的充值记录
const totalRechargeAmount = computed(() => {
  return paymentRecords.value
    .filter(r => r.payment_type === 'recharge' && r.status !== 'revoked')
    .reduce((sum, record) => sum + Number(record.amount), 0)
})

// 扣款总金额计算 - 统计所有有效的扣款记录
const totalDeductionAmount = computed(() => {
  return paymentRecords.value
    .filter(r => r.payment_type === 'deduction' && r.status !== 'revoked')
    .reduce((sum, record) => sum + Number(record.amount), 0)
})

// 当前余额计算 - 充值总额减去扣款总额
const currentBalance = computed(() => {
  return totalRechargeAmount.value - totalDeductionAmount.value
})

// 重新计算所有记录余额
function recalculateAllBalances() {
  
  if (paymentRecords.value.length === 0) {
    return
  }
  
  try {
    // 过滤有效记录（排除已撤销的记录）
    const validRecords = paymentRecords.value.filter(record => record.status !== 'revoked')
    
    // 时间格式化和排序
    const normalizeDate = (dateStr: string) => {
      return dateStr.replace(/(\d{4})\/(\d{1,2})\/(\d{1,2})/, (match: string, year: string, month: string, day: string) => {
        return `${year}-${month.padStart(2, '0')}-${day.padStart(2, '0')}`
      })
    }
    
    const sortedRecords = [...validRecords].sort((a, b) => {
      const dateA = new Date(normalizeDate(a.payment_date)).getTime()
      const dateB = new Date(normalizeDate(b.payment_date)).getTime()
      return dateA - dateB
    })
    
    // 逐步计算余额
    let currentBalance = 0
    const balanceHistory: Array<{recordId: string, calculatedBalance: number, balanceText: string}> = []
    
    sortedRecords.forEach((record) => {
      const amount = Number(record.amount)
      
      // 验证金额数据
      if (isNaN(amount)) {
        console.error(`记录 ${record.id} 的金额无效: "${record.amount}"`)
        return
      }
      
      // 特殊处理REVERSE记录 - 显示撤销前的余额状态
      if (record.id.startsWith('REVERSE')) {
        const balanceText = currentBalance >= 0 
          ? `¥${currentBalance.toLocaleString()}` 
          : `-¥${Math.abs(currentBalance).toLocaleString()}`
        
        balanceHistory.push({
          recordId: record.id,
          calculatedBalance: currentBalance, // 保持撤销前的余额
          balanceText: balanceText
        })
        return
      }
      
      // 普通记录的余额计算
      if (record.payment_type === 'recharge') {
        currentBalance += amount
      } else if (record.payment_type === 'deduction') {
        currentBalance -= amount
      }
      
      // 格式化余额文本
      const balanceText = currentBalance >= 0 
        ? `¥${currentBalance.toLocaleString()}` 
        : `-¥${Math.abs(currentBalance).toLocaleString()}`
      
      balanceHistory.push({
        recordId: record.id,
        calculatedBalance: currentBalance,
        balanceText: balanceText
      })
    })
    
    // 更新记录余额
    paymentRecords.value.forEach(record => {
      const historyItem = balanceHistory.find(h => h.recordId === record.id)
      if (historyItem) {
        record.balance = historyItem.balanceText
      } else if (record.status === 'revoked') {
        // 已撤销的记录保持原有余额，不设置为"-"
      }
    })
    
    // 重新排序用于显示（最新的在前）
    paymentRecords.value.sort((a, b) => {
      const dateA = new Date(normalizeDate(a.payment_date)).getTime()
      const dateB = new Date(normalizeDate(b.payment_date)).getTime()
      return dateB - dateA
    })
    
  } catch (error) {
    console.error('❌ 余额计算出错:', error)
  }
}

// 检查是否可以撤销（30天内）
function canRevoke(row: any): boolean {
  // 如果不是成功状态，不能撤销
  if (row.status !== 'success') {
    return false
  }
  
  // 检查是否在30天内
  const paymentDate = new Date(row.payment_date)
  const currentDate = new Date()
  const timeDiff = currentDate.getTime() - paymentDate.getTime()
  const daysDiff = timeDiff / (1000 * 3600 * 24)
  
  // 超过30天不能撤销
  return daysDiff <= 30
}

// 撤销支付
function revokePayment(row: any) {
  const isRefund = row.id.startsWith('REFUND')
  const isReverse = row.id.startsWith('REVERSE')
  const operationName = isRefund ? '退款' : (isReverse ? '撤销操作' : (row.payment_type === 'recharge' ? '充值' : '扣款'))
  
  // 检查撤销操作是否会导致余额为负数
  const recordIndex = paymentRecords.value.findIndex(r => r.id === row.id)
  if (recordIndex === -1) return
  
  // 计算撤销后的预期余额
  let expectedBalance = 0
  const sortedRecords = [...paymentRecords.value].sort((a, b) => {
    const dateA = new Date(a.payment_date).getTime()
    const dateB = new Date(b.payment_date).getTime()
    return dateA - dateB
  })
  
  // 模拟撤销操作后的余额（只计算撤销前的记录）
  let tempBalance = 0
  const revokeRecordDate = new Date(row.payment_date).getTime()
  
  for (let i = 0; i < sortedRecords.length; i++) {
    const record = sortedRecords[i]
    
    // 只计算撤销记录时间点之前的记录
    const recordDate = new Date(record.payment_date).getTime()
    if (recordDate > revokeRecordDate) continue
    
    // 跳过当前要撤销的记录
    if (record.id === row.id) continue
    
    // 移除跳过已撤销记录的判断，所有记录都参与计算
    
    const amount = Number(record.amount)
    
    if (record.payment_type === 'recharge') {
      tempBalance += amount
    } else if (record.payment_type === 'deduction') {
      tempBalance = Math.max(0, tempBalance - amount)
    }
  }
  
  // 计算撤销操作的影响
  const revokeAmount = Number(row.amount)
  let newExpectedBalance = tempBalance
  
  if (row.payment_type === 'recharge') {
    // 撤销充值 = 扣款
    newExpectedBalance = Math.max(0, tempBalance - revokeAmount)
  } else {
    // 撤销扣款 = 充值
    newExpectedBalance = tempBalance + revokeAmount
  }
  
  // 检查是否会为负数
  if (newExpectedBalance < 0) {
    ElMessageBox.alert(
      `撤销此${operationName}记录会导致会员余额变为负数（¥${newExpectedBalance}），无法撤销。`,
      '撤销失败',
      {
        confirmButtonText: '知道了',
        type: 'warning'
      }
    )
    return
  }
  
  ElMessageBox.confirm(
    `确定要撤销这笔${operationName}记录吗？撤销后将生成撤销操作记录。`,
    '确认撤销',
    {
      confirmButtonText: '确定撤销',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    // 执行撤销操作
    if (recordIndex !== -1) {
      // 在改变状态前，保存当前的正确余额（撤销前应该显示的余额）
      const originalBalance = paymentRecords.value[recordIndex].balance
      
      // 更新原记录状态为已撤销
      paymentRecords.value[recordIndex].status = 'revoked'
      paymentRecords.value[recordIndex].remark = (paymentRecords.value[recordIndex].remark || '') + ' (已撤销)'
      paymentRecords.value[recordIndex].is_revoked = 1
      
      // 保持原有余额显示，不设置为"-"
      paymentRecords.value[recordIndex].balance = originalBalance
      
      // 根据原记录类型确定撤销操作类型
      let reversePaymentType: 'recharge' | 'deduction'
      let reverseRemark: string
      
      if (row.payment_type === 'recharge') {
        // 充值撤销 -> 生成扣款记录
        reversePaymentType = 'deduction'
        reverseRemark = `撤销充值记录`
      } else {
        // 扣款撤销 -> 生成充值记录
        reversePaymentType = 'recharge'
        reverseRemark = `撤销扣款记录`
      }
      
      // 生成撤销记录
      // 使用当前时间作为撤销操作的时间
      const currentTime = new Date()
      
      const reverseRecord: PaymentRecord = {
        id: `REVERSE${String(100000 + paymentRecords.value.length).slice(1)}`,
        member_id: row.member_id,
        payment_type: reversePaymentType,
        amount: row.amount,
        balance: '',
        currency: 'JPY',
        payment_channel: row.payment_channel,
        remark: reverseRemark,
        status: 'success',
        // 使用当前时间，记录撤销操作发生的时间
        payment_date: currentTime.toLocaleString(),
        transaction_id: `TXN${Date.now()}`,
        create_time: currentTime.toLocaleString(),
        operator: '管理员',
        related_record_id: row.id,
        is_revoked: 0
      }

      // 保存撤销记录到数据库
      try {
        await savePaymentRecordAPI(reverseRecord)
        console.log('撤销记录已保存到数据库:', reverseRecord.id)
        
        // 直接插入原记录后方，保持时间顺序
        paymentRecords.value.splice(recordIndex + 1, 0, reverseRecord)
        
        // 重新计算所有记录的余额
        recalculateAllBalances()
        
        ElMessage.success(`撤销成功！已生成撤销操作记录`)
      } catch (error) {
        console.error('保存撤销记录失败:', error)
        ElMessage.error('撤销失败，请重试')
      }
    }
  }).catch(() => {
    // 用户取消
  })
}

// 工具函数
function getChannelName(channel: string) {
  const channelMap: Record<string, string> = {
    alipay: '支付宝',
    wechat: '微信支付',
    bank: '银行卡',
    paypal: 'PayPal',
    scan: '扫码充值',
    wire: '国际汇款',
    other: '其他',
    transfer: '转给好友',
    withdraw: '余额提现',
    '好友转账': '好友转账'
  }
  return channelMap[channel] || channel
}

function getStatusName(status: string) {
  const statusMap: Record<string, string> = {
    success: '成功',
    failed: '失败',
    pending: '处理中',
    revoked: '已撤销'
  }
  return statusMap[status] || status
}

function getStatusType(status: string) {
  const typeMap: Record<string, string> = {
    success: 'success',
    failed: 'danger',
    pending: 'warning',
    revoked: 'info'
  }
  return typeMap[status] || 'info'
}

// 复制到剪贴板
async function copyToClipboard(text: string) {
  try {
    await navigator.clipboard.writeText(text)
    ElMessage.success('关联订单ID已复制到剪贴板')
  } catch (error) {
    // 降级方案：使用传统方法
    const textArea = document.createElement('textarea')
    textArea.value = text
    document.body.appendChild(textArea)
    textArea.select()
    try {
      document.execCommand('copy')
      ElMessage.success('关联订单ID已复制到剪贴板')
    } catch (err) {
      ElMessage.error('复制失败，请手动复制')
    }
    document.body.removeChild(textArea)
  }
}

// 搜索和重置
function onSearch() {
  currentPage.value = 1
}

function onReset() {
  searchForm.value = {
    paymentType: '',
    paymentChannel: '',
    status: '',
    dateRange: []
  }
  currentPage.value = 1
}

// 查看明细
function viewDetail(row: any) {
  detailData.value = row
  showDetailDialog.value = true
}
</script>

<style scoped>
.payment-detail-tab {
  padding: 20px;
}

.info-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
}

.label {
  color: #606266;
  font-size: 14px;
}

.value {
  font-weight: 600;
  color: #303133;
}

.amount-positive {
  color: #67c23a;
  font-weight: 600;
}

.amount-negative {
  color: #f56c6c;
  font-weight: 600;
}

.payment-summary {
  margin: 16px 0;
  padding: 16px;
  background: #f5f7fa;
  border-radius: 8px;
}

.summary-item {
  text-align: center;
  padding: 16px;
  background: white;
  border-radius: 6px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.summary-label {
  color: #606266;
  font-size: 14px;
  margin-bottom: 8px;
}

.summary-value {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
}

.recharge-total {
  color: #67c23a;
}

.deduction-total {
  color: #f56c6c;
}

.current-balance {
  color: #409eff;
}

.balance-positive {
  color: #67c23a;
  font-weight: 600;
}

.balance-negative {
  color: #f56c6c;
  font-weight: 600;
}
</style> 